package com.anjie.powerproject.schedule;

import com.anjie.powerproject.common.Result;
import com.anjie.powerproject.entity.Device;
import com.anjie.powerproject.service.DeviceService;
import com.anjie.powerproject.service.StrategyOutputService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * 设备最大工况自调节定时任务
 */
@RestController
@RequestMapping(value = "schedule/device_power")
public class DeviceMaxPowerSchedule {
    private static final Logger logger = LoggerFactory.getLogger(DeviceMaxPowerSchedule.class);

    @Autowired
    StrategyOutputService strategyOutputService;

    @Autowired
    DeviceService deviceService;

    @RequestMapping(value = "excute")
    public Result<Void> excute() {
        try {
            scheduleTask();
            return Result.ok(null);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return Result.error(String.format("[%s]", ex.getMessage()));
        }
    }

    /**
     * 设定在得到每天的预测数据之后执行
     */
    @Scheduled(cron = "0 0 23 * * ?")
    private void scheduleTask() {
        logger.info("最大功率自调节定时任务启动");

        // 首先查询所有的设备
        List<Device> devices = deviceService.getAllDevices();

        for (Device device : devices) {
            // 只有开启了设备最大功率自调节的设备才会继续
            if (device.getPowerMonitorSwitch() == null || device.getPowerMonitorSwitch() == 0) {
                continue;
            }

            // 使用设备id从strategy_output中去查询最近N次使用该设备时的功率
            List<Float> powerList = strategyOutputService.getPowerInStrategy(device.getDeviceId(), device.getAutoAdjustLastTime());

            // 如果连续N天都未达到设备的最大功率，将设备最大功率设置为N天内的最大值
            long count = powerList.stream().filter(power -> power < device.getPower()).count();
            if (count == powerList.size()) {
                float originPower = device.getPower();

                Optional<Float> maxOptional = powerList.stream().max(Float::compareTo);
                maxOptional.ifPresent(device::setPower);

                deviceService.saveAndFlush(device);

                logger.info("对设备{}进行最大功率自调节，将最大功率由{}调整为{}", device.getDeviceName(), originPower, device.getPower());
            }
        }
    }
}
